package com.example.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueDemo {

	public static void main(String[] args) throws Exception {
		BlockingQueue<String> queue = new ArrayBlockingQueue<String>(3);
		
//		test1(queue);
//		test2(queue);
//		test3(queue);
		test4(queue);
	}

	public static void test1(BlockingQueue<String> queue) {
		System.out.println(queue.add("a"));
		System.out.println(queue.add("b"));
		System.out.println(queue.add("c"));
//		System.out.println(queue.element());
		// 队列满了时，add方法会抛出异常
//		System.out.println(queue.add("d"));

		System.out.println(queue.remove());
		System.out.println(queue.remove());
		System.out.println(queue.remove());
		// 队列为空时，remove方法会抛出异常
//		System.out.println(queue.remove());
	}

	public static void test2(BlockingQueue<String> queue) {
		System.out.println(queue.offer("a"));
		System.out.println(queue.offer("b"));
		System.out.println(queue.offer("c"));
		// 队列满了时，offer方法会返回false
		System.out.println(queue.offer("d"));
		
		System.out.println("----------------------");
		System.out.println(queue.poll());
		System.out.println(queue.poll());
		System.out.println(queue.poll());
		// 队列为空时，返回null
		System.out.println(queue.poll());
		
	}
	
	public static void test3(BlockingQueue<String> queue) throws Exception {
		queue.put("a");
		queue.put("b");
		queue.put("c");
		// 队列满了时，put方法会阻塞等待
//		queue.put("d");
		
		System.out.println("----------------------");
		System.out.println(queue.take());
		System.out.println(queue.take());
		System.out.println(queue.take());
		// 队列为空时，take方法会阻塞等待
		System.out.println(queue.take());
		
	}
	
	public static void test4(BlockingQueue<String> queue) throws Exception {
		System.out.println(queue.offer("a", 2, TimeUnit.SECONDS));
		System.out.println(queue.offer("b", 2, TimeUnit.SECONDS));
		System.out.println(queue.offer("c", 2, TimeUnit.SECONDS));
		System.out.println(queue.offer("d", 2, TimeUnit.SECONDS));
		// 队列满了时，offer方法会阻塞等待指定时间
//		queue.put("d");
		
		System.out.println("----------------------");
		System.out.println(queue.poll(2, TimeUnit.SECONDS));
		System.out.println(queue.poll(2, TimeUnit.SECONDS));
		System.out.println(queue.poll(2, TimeUnit.SECONDS));
		// 队列为空时，take方法会阻塞等待指定时间
		System.out.println(queue.poll(2, TimeUnit.SECONDS));
		
	}
}
